var fs = require("fs");
var crypto = require("crypto");
module.exports = {
	get: function(url_hash) {
		var filepath = "db/" + url_hash.split("").join("/") + ".url";
		try {
			return fs.readFileSync(filepath)
		} catch (e) {
			throw "无效HASH"
		}
	},
	build: function(url) {
		if (!url) {
			throw "参数错误"
			return;
		}
		var hasher = crypto.createHash("md5");
		hasher.update(url);
		var hashmsg = hasher.digest('hex');
		var arr = (hashmsg + hashmsg).split(""); //避免重复而导致的冲突
		var path = [];
		if (!fs.existsSync("db")) {
			fs.mkdirSync("db");
		}
		var result;
		(function _getPath() {
			if (!arr.length) {
				throw "短地址生成失败";
			}
			path.push(arr.shift())
			var currentPath = "db/" + path.join("/");
			//创建相应目录
			if (!fs.existsSync(currentPath)) {
				fs.mkdirSync(currentPath);
			}
			//是否有相应URL对象
			if (fs.existsSync(currentPath + ".url")) {
				if (fs.readFileSync(currentPath + ".url").toString() === url) {
					result = path.join("");
					return;
				}
				_getPath();
			} else {
				//如果没有则使用到当前的路径
				fs.writeFileSync(currentPath + ".url", url);
				result = path.join("");
			}
		}());
		return result;
	}
}